package com.xinlianshiye.im.utils;

import com.xinlianshiye.im.response.ImageView;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class ImageUpload {

    public static <T> ImageView upload(Class<T> beanClass, MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        if (!isImage(filename)) {
            // throw LOG.err("typeErr", "image type is not supported, it must in \"jpg,png,gif,bmp,jpeg\"");
        }
        String suffix = suffix(filename);
        String targetName = DigestUtils.md5Hex(file.getInputStream());
        String url = OssUtil.upload(beanClass, targetName + suffix, file.getInputStream());
        ImageView view = new ImageView();
        view.setName(targetName + suffix);
        view.setOriginalName(filename);
        view.setSize(file.getSize());
        view.setState("SUCCESS");
        view.setType(suffix.substring(1));
        view.setUrl(url);
        return view;
    }

    public static String suffix(String filename) {
        return filename.substring(filename.lastIndexOf("."));
    }

    public static boolean isImage(String fn) {
        fn = fn.toLowerCase();
        return fn.endsWith(".jpg")
                || fn.endsWith(".png")
                || fn.endsWith(".gif")
                || fn.endsWith(".bmp")
                || fn.endsWith(".jpeg");
    }
}
